package org.eduapp.trains.web.action.account;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.eduapp.trains.ServiceException;
import org.eduapp.trains.model.account.ModelAccount;
import org.eduapp.trains.model.account.ModelRoles;
import org.eduapp.trains.service.account.AccountService;
import org.eduapp.trains.web.action.BaseAction;

/**
 * 
 * @author jeccy
 *
 */
public class AccountAction extends BaseAction {
	
	private AccountService accountService;
	
	
	/**
	 * Account login action
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward accountLogin (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		if(null!=cookies){
			for(Cookie cookie : cookies){
	           if(cookie.getName().equals("j_username")){
	        	   request.setAttribute("username", cookie.getValue());
	           }
	           if(cookie.getName().equals("j_password")){
	        	   request.setAttribute("password", cookie.getValue());
	           }
	        }
	    }
		return mapping.findForward("index");
	}
	
	
	
	public ActionForward accountLoginAuth(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			HttpSession session=request.getSession();//获得session对象
			String username=request.getParameter("username");
			String password=request.getParameter("password");	
			ModelAccount account=accountService.getAccountAuth(username,password);
			if (account!=null) {
				String j_rememberPWD = request.getParameter("j_rememberPWD");
				if("true".equals(j_rememberPWD)){
					Cookie cookie1 = new Cookie("j_username",username);
					Cookie cookie2 = new Cookie("j_password",password);
					cookie1.setMaxAge(3600);
					cookie2.setMaxAge(3600);
					cookie2.setPath("/"); 
					cookie1.setPath("/");
					response.addCookie(cookie1);
					response.addCookie(cookie2);
				}else{
					Cookie cookie1 = new Cookie("j_username",null);
					Cookie cookie2 = new Cookie("j_password",null);
					cookie1.setPath("/");
					cookie2.setPath("/"); 
					response.addCookie(cookie1);
					response.addCookie(cookie2);
				}
				//session.put("USER",account);
				session.putValue("USER",account);
				
				//session.put("AUTH_MENUS",user.getRoleModel().getMenus());
				/**
				if(Integer.parseInt(user.getRoleModel().getId()) >= 3){//企业用户
					String companyId=eBaseService.getByUserID(user.getId()).toString();
					session.put(BaseAction.BASEIDINSESSION, companyId);
					session.put("CompanyName", eBaseService.get(companyId).getEnterpriseName());
				}*/			
				return ajaxPrint(response,"success");
			}
			return ajaxPrint(response,"userFail");
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxPrint(response,"execption");
		}
	
	}
	
	public ActionForward accountLoginOut(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		
		
		HttpSession session=request.getSession();//获得session对象
		//session.removeValue("USER");
		session.invalidate(); 
		//session.remove("GOING_TO");
		
		Cookie[] cookies = request.getCookies();
		if(null!=cookies){
			for(Cookie cookie : cookies){
	           if(cookie.getName().equals("j_username")){
	        	   request.setAttribute("username", cookie.getValue());
	           }
	           if(cookie.getName().equals("j_password")){
	        	   request.setAttribute("password", cookie.getValue());
	           }
	        }
	    }
		return mapping.findForward("index");
	}
	
	
	
	/**
	 * Account register action
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward accountRegister (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Implement ME
		return null;
	}
	
	/**
	 * Account logout action
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward accountLogout (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Implement ME
		return null;
	}
	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward accountPersonalCenterIndex (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		return mapping.findForward("account.personal.center");
	}
	
	/**
	 * Account manage index action
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward accountManageIndex (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Implement ME
		//int role=Session.g
		
			HttpSession session=request.getSession();//获得session对象
			ModelAccount account=(ModelAccount) session.getAttribute("USER");
			//String role=account.getAccountRole().getRole_id();
			if(!account.getAccountRole().getRole_id().equals("1")){
				return mapping.findForward("home.index");
			}else{
				return mapping.findForward("admin.account.manage");
			}
		
		
	}
	
	/**
	 * �û��б�
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws ServiceException 
	 */
	public ActionForward accountManageList (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws ServiceException {
		// TODO Implement ME
		int offset = request.getParameter("page") == null ? 0 : 
			(Integer.parseInt(request.getParameter("page")) - 1)*5;

		//if()
		ModelAccount account=(ModelAccount)form;
		String name=account.getAccountRealName();
		String cla=account.getAccountClass();
		String num=account.getAccountNo();
		String maj=account.getAccountMajority();
		
		request.getSession().setAttribute("accountRealName", name);
		request.getSession().setAttribute("accountClass", cla);
		request.getSession().setAttribute("accountNo", num);
		request.getSession().setAttribute("accountMajority", maj);
		
		
		if(maj!=null){
			account.setAccountMajority(maj);
		}
		if(name!=null){
			account.setAccountRealName(name);
		}
		if(cla!=null){
			account.setAccountClass(cla);
		}
		if(num!=null){
			account.setAccountNo(num);
		}
		
		//request.setAttribute("result", accountService.getByModel(account));
		request.setAttribute("result.page", accountService.get(account, 5, offset, null, null));
		
		
		
		return mapping.findForward("admin.account.manage");
	}
	
	
	public ActionForward accountManagePage (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws ServiceException {
		
		int offset = request.getParameter("page") == null ? 0 : 
			(Integer.parseInt(request.getParameter("page")) - 1)*5;
		
		String name=(String) request.getSession().getAttribute("accountRealName");
		String cla=(String)request.getSession().getAttribute("accountClass");
		String num=(String)request.getSession().getAttribute("accountNo");
		String maj=(String)request.getSession().getAttribute("accountMajority");
		
		ModelAccount account=new ModelAccount();
		
		if(maj!=null){
			account.setAccountMajority(maj);
		}
		if(name!=null){
			account.setAccountRealName(name);
		}
		if(cla!=null){
			account.setAccountClass(cla);
		}
		if(num!=null){
			account.setAccountNo(num);
		}
		
		request.setAttribute("result.page", accountService.get(account, 5, offset, null, null));
		
		return mapping.findForward("admin.account.manage");
	}
	
	/**
	 * ��ת�����ҳ��
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws ServiceException
	 */
	public ActionForward accountManageIntoadd (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws ServiceException {
				return mapping.findForward("intoadd");
	}
	
	/**
	 * ����û�
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws ServiceException
	 */
	public ActionForward accountManageAdd (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws ServiceException {
		ModelAccount account=(ModelAccount)form;
		String no=account.getAccountNo();
		String pass=account.getAccountPassword();
		String name=account.getAccountRealName();
		String maj=account.getAccountMajority();
		String grade=account.getAccountGrade();
		String cls=account.getAccountClass();
		String iden=account.getAccountIdentification();
		String mobile=account.getAccountMobilePhone();
		int role=account.getAccount_role();
		
		
		
		account.setAccountNo(no);
		account.setAccountPassword(pass);
		account.setAccountRealName(name);
		account.setAccountClass(cls);
		account.setAccountGrade(grade);
		account.setAccountIdentification(iden);
		account.setAccountMajority(maj);
		ModelRoles mr=new ModelRoles();
		mr.setRole_id(String.valueOf(role));
		account.setAccountRole(mr);
		//account.setAccount_role(role);
		account.setAccountMobilePhone(mobile);
		account.setAccountStatus(0);
		//account.setAccountRole(accountRole)
		if(accountService.getByNo(no)!=null){
			accountService.saveOrUpdate(account);
			return ajaxPrint(response, "添加成功");
		}else{
			return ajaxPrint(response, "添加失败");
		}
		
		
	}
	
	/**
	 * �����û�
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws ServiceException
	 */
	public ActionForward accountManageFind (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws ServiceException {
				//status=0Ϊδ���
				ModelAccount account=new ModelAccount();
				account.setAccountStatus(0);
				request.setAttribute("result.page", accountService.get(account, 5, 0, null, null));
				return null;
		
	}
	
	public ActionForward accountManageCheck (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws ServiceException {
				
				return null;
	}
	
	/**ɾ���û�
	 * Account manage remove action
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws ServiceException 
	 */
	public ActionForward accountManageRemove (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws ServiceException {
		// TODO Implement ME
		String id=request.getParameter("id");
		accountService.remove(id);
		return null;
	}
	/**
	 * �û���ϸ��Ϣ
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws ServiceException
	 */
	public ActionForward accountManageDetail (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws ServiceException {
		String id=request.getParameter("id");
		request.setAttribute("result", accountService.get(id));
		return mapping.findForward("admin.account.detail");
		
	}
	
	/**
	 * �޸�����
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws ServiceException
	 */
	public ActionForward accountManagePasschange (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws ServiceException {
		String id=request.getParameter("id");
		String pass=request.getParameter("pass");
		ModelAccount account=accountService.get(id);
		account.setAccountPassword(pass);
		accountService.saveOrUpdate(account);
		return ajaxPrint(response,"true");
		
	}
	
	/**
	 * Account manage creation action
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward accountManageCreate (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Implement ME
		return null;
	}
	
	/**
	 * 
	 * ����δ�����҄1�7
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward accountManageFinduncheck (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Implement ME
		
		return null;
	}
	/**
	 * ��excel�е���
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward accountManageImport (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String path=(String) request.getParameter("path");
		
		try
		{
		// ����Workbook����, ֻ��Workbook����
		// ֱ�Ӵӱ����ļ�����Workbook
		// ���������Workbook

		System.out.println("start load file-------------------------");
		InputStream is = new FileInputStream("E:/"+path);//��������

		jxl.Workbook rwb = Workbook.getWorkbook(is);
		Sheet rs = rwb.getSheet(0); //��ȡ��һ��sheet
		int colNum=rs.getColumns();//����
		int rowNum=rs.getRows();//����
		//System.out.println(colNum+" "+rowNum);
		//����account  bean
		/*ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{
				"spring/applicationContext-model-account.xml","spring/applicationContext.xml"});
		AccountService g= (AccountService) ctx.getBean("accountService");*/
		for (int i = 1; i <rowNum; i++) {
			String no=rs.getCell(0, i).getContents();
			String pass=rs.getCell(1,i).getContents();
			String name=rs.getCell(2,i).getContents();
			String maj=rs.getCell(3, i).getContents();
			String grade=rs.getCell(4,i).getContents();
			String cla=rs.getCell(5,i).getContents();
			String idn=rs.getCell(6, i).getContents();
			String email=rs.getCell(7,i).getContents();
			String phone=rs.getCell(8,i).getContents();
			String status=rs.getCell(9, i).getContents();
			String role=rs.getCell(10,i).getContents();
			
			ModelAccount ma=new ModelAccount();
			ma.setAccountNo(no);
			ma.setAccountPassword(pass);
			ma.setAccountRealName(name);
			ma.setAccountMajority(maj);
			ma.setAccountGrade(grade);
			ma.setAccountClass(cla);
			ma.setAccountIdentification(idn);
			ma.setAccountEmail(email);
			ma.setAccountMobilePhone(phone);
			ma.setAccountStatus(0);
			ModelRoles ac=new ModelRoles();
			ac.setRole_id(role);
			ma.setAccountRole(ac);
			accountService.saveOrUpdate(ma);
			//ma.setAccount_role(account_role)
			//System.out.println(no);
		}
		
		}
		
		catch (Exception e)
		{
		e.printStackTrace();
		}
		
		return ajaxPrint(response,"success");
	}
	
	/**
	 * Excel����
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws ServiceException 
	 */
	public ActionForward accountManageExport (ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws ServiceException {
		
		String name=request.getParameter("name");
		String no=request.getParameter("no");
		String maj=request.getParameter("maj");
		String cla=request.getParameter("cla");
		
		ModelAccount account=new ModelAccount();
		if(maj!=null){
			account.setAccountMajority(maj);
		}
		if(name!=null){
			account.setAccountRealName(name);
		}
		if(cla!=null){
			account.setAccountClass(cla);
		}
		if(no!=null){
			account.setAccountNo(no);
		}
		List<ModelAccount> list=accountService.getByModel(account);
		
		try
		{
		File file = new File("e:/����1.xls");
		// ���ļ�
		WritableWorkbook book = Workbook.createWorkbook(file);
		WritableSheet sheet = book.createSheet("��һҳ", 0);
		// �Լ���Ԫ������Ϊtest
		Label label0 = new Label(0, 0, "�û��嵥");
		Label label1 = new Label(0, 1, "ѧ��");
		Label label2 = new Label(1, 1, "����");
		Label label3 = new Label(2, 1, "����");
		Label label4 = new Label(3, 1, "רҵ");
		Label label5 = new Label(4, 1, "�꼶");
		Label label6 = new Label(5, 1, "�༶");
		Label label7 = new Label(6, 1, "���֤");
		Label label8 = new Label(7, 1, "�����ʼ�");
		Label label9 = new Label(8, 1, "�ֻ�");
		Label label10 = new Label(9, 1, "״̬");
		Label label11 = new Label(10, 1, "����");
		// ������õĵ�Ԫ����ӵ��������
		sheet.addCell(label0);//�ϲ���Ԫ��
		//��col1�е�col2�� ��row1�е�row2��//
		//mergecells(int col1, int row1, int col2, int row2);
		//sheet.mergeCells(0, 0, 3, 0);
		sheet.addCell(label1);
		sheet.addCell(label2);
		sheet.addCell(label3);
		sheet.addCell(label4);
		sheet.addCell(label5);
		sheet.addCell(label6);
		sheet.addCell(label7);
		sheet.addCell(label8);
		sheet.addCell(label9);
		sheet.addCell(label10);
		sheet.addCell(label11);
		for(int i=0;i<list.size();i++){
			ModelAccount ma=list.get(i);
			Label lab0 = new Label(0, i + 2, ma.getAccountNo());
			Label lab1 = new Label(1, i + 2, ma.getAccountPassword());
			Label lab2 = new Label(2, i + 2, ma.getAccountRealName());
			Label lab3 = new Label(3, i + 2, ma.getAccountMajority());
			Label lab4 = new Label(4, i + 2, ma.getAccountGrade());
			Label lab5 = new Label(5, i + 2, ma.getAccountClass());
			Label lab6 = new Label(6, i + 2, ma.getAccountIdentification());
			Label lab7 = new Label(7, i + 2, ma.getAccountEmail());
			Label lab8 = new Label(8, i + 2, ma.getAccountMobilePhone());
			Label lab9 = new Label(9, i + 2, String.valueOf(ma.getAccountStatus()));
			Label lab10 = new Label(10, i + 2, String.valueOf(ma.getAccountRole().getRole_id()));
			sheet.addCell(lab0);
			sheet.addCell(lab1);
			sheet.addCell(lab2);
			sheet.addCell(lab3);
			sheet.addCell(lab4);
			sheet.addCell(lab5);
			sheet.addCell(lab6);
			sheet.addCell(lab7);
			sheet.addCell(lab8);
			sheet.addCell(lab9);
			sheet.addCell(lab10);
			
		}
		book.write();
		book.close();
		}
		
		catch (Exception e)
		{
		e.printStackTrace();
		}
		return ajaxPrint(response,"success");
		
	}
	
	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}

	public AccountService getAccountService() {
		return accountService;
	}
	
}
